using Domain.Entities;
using Domain.Services;
using Domain.Permissions;
using System;
using System.Web.UI.WebControls;
using UserInterface.Misc;

namespace UserInterface
{
    public partial class MoveTopic : BoardPageBase
    {
        private Topic topic;
        
        protected void Page_Load(object sender, EventArgs e)
        {
            int topicId = Convert.ToInt32(Request.QueryString["topicId"]);
            string pageTitle = (string)GetLocalResourceObject("Title");

            topic = TopicService.GetById(topicId);
            ForumPermissionManager forumPermissionManager = PermissionManager.CreateForumPermissionManager(topic.Forum);

            if (!forumPermissionManager.Moderate)
            {
                DieMessage(DieMessageType.InsufficientPermissions, "InsufficientPermissions");
            }

            MasterPage.TitleGenerator.PageTitle = pageTitle;
            MasterPage.TitleGenerator.ItemName = topic.Subject;
            MasterPage.HeaderText = pageTitle + ": " + topic.Subject;
            MasterPage.AddPathItem(topic.Forum.Name, "ViewForum.aspx?forumId=" + topic.Forum.Id);
            MasterPage.AddPathItem(topic.Subject, "ViewTopic.aspx?topicId=" + topic.Id);
            MasterPage.AddPathItem(pageTitle, "MoveTopic.aspx?topicId=" + topic.Id);

            if (!IsPostBack)
            {
                CategoryRepeater.DataSource = CategoryService.GetAll();
                CategoryRepeater.DataBind();
            }
        }

        protected void ForumRepeater_ItemCommand(object sender, RepeaterCommandEventArgs e)
        {
            short forumId = short.Parse((string)e.CommandArgument);
            Forum forum = ForumService.GetById(forumId);
            TopicService.MoveTopic(topic, forum);
            Response.Redirect("ViewTopic.aspx?topicId=" + topic.Id);
        }

        protected void ForumRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Forum forum = e.Item.DataItem as Forum;
                Button moveButton = e.Item.FindControl("MoveButton") as Button;
                moveButton.Visible = topic.Forum.Id != forum.Id;
            }
        }

        protected int TopicId
        {
            get { return topic.Id; }
        }
    }
}
